package com.gitee.kamismile.stoneComEx.common.component.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.kamismile.stoneComEx.common.Constant;
import com.gitee.kamismile.stoneComEx.common.component.support.annotation.SecurityParameter;
import com.gitee.kamismile.stoneComEx.util.SecretCodeUtil;
import com.gitee.kamismile.stone.commmon.util.ValueUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

public class EncryptResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Class converterType) {
        return methodParameter.getMethodAnnotation(SecurityParameter.class) != null
                && methodParameter.getParameterAnnotation(RequestBody.class) != null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter parameter, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        SecurityParameter requestDecode = parameter.getMethodAnnotation(SecurityParameter.class);
        if (ValueUtils.isNull(requestDecode)) {
            return request;
        }

        boolean outEncode = requestDecode.outEncode();

        if (outEncode) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
                return SecretCodeUtil.encrypt(result, Constant.SECODE,SecretCodeUtil.BLOWFISH);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return body;

    }
}
